<template>
  <div class="userApply">
    <div class="userApply-header">
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="所属城市" prop="cityCode">
            <el-tree-select
              v-model="formSearch.cityCode"
              :data="cityTreeOption"
              :props="defaultProps"
              :render-after-expand="false"
              node-key="Code"
              check-strictly
              @change="cs11"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.activityvenuescode"
              placeholder="--选择--"
              filterable
              clearable
            >
              <el-option
                v-for="item in activityVenuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select
              v-model="formSearch.Role"
              placeholder="--请选择--"
              filterable
              clearable
            >
              <el-option
                v-for="item in rolesOption"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申请人姓名">
            <!-- <el-select v-model="formSearch.driver" placeholder="--选择--">
              <el-option
                v-for="item in driverOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
            <el-input
              v-model="formSearch.ApplyUserId"
              placeholder="申请人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否通过">
            <el-select
              v-model="formSearch.IsThrough"
              placeholder="--选择--"
              clearable
            >
              <el-option
                v-for="item in isOnlineOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="userApply-list">
      <el-row class="batchaction" style="display: none">
        <el-col>
          <el-button
            size="small"
            type="primary"
            v-btnpermission="'btn-applyupdate'"
            :icon="Edit"
            @click="batchApprove"
            >批量通过</el-button
          >
          <el-button
            size="small"
            type="danger"
            v-btnpermission="'btn-applydelete'"
            @click="batchDeny"
            :icon="Delete"
            >批量拒绝</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table
            :data="ApplyUserList"
            @selection-change="handleSelectionChange"
            border
            stripe
          >
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="cityName" label="所属城市"></el-table-column>
            <el-table-column prop="venuesName" label="场馆"></el-table-column>
            <el-table-column prop="roleName" label="角色"></el-table-column>
            <!-- <el-table-column
              prop="ApplyTime"
              label="申请时间"
              :formatter="timeFormat"
            ></el-table-column> -->
            <el-table-column
              prop="applyUserName"
              label="申请人姓名"
            ></el-table-column>
            <el-table-column prop="IsThrough" label="是否通过">
              <template #default="scope">
                <el-tag
                  class="mx-1"
                  effect="dark"
                  :type="
                    scope.row.ApproveUserID == 0
                      ? 'warning'
                      : scope.row.IsThrough
                      ? ''
                      : 'info'
                  "
                >
                  {{
                    scope.row.ApproveUserID == 0
                      ? '未审核'
                      : scope.row.IsThrough
                      ? '通过'
                      : '拒绝'
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="RefuseReason"
              label="未通过原因"
            ></el-table-column>
            <el-table-column
              prop="Telephone"
              label="联系电话"
            ></el-table-column>
            <el-table-column
              prop="ApproveUserName"
              label="审核人姓名"
            ></el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-applyupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >审核</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-applydelete'"
                  @click="rowDelete(scope.row.SerialNumber)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog title="审核页面" v-model="editDialogVisible" width="40%">
        <el-form
          :model="editDialogForm"
          :rules="ambulanceFormRulesMixin.editFormRules"
          ref="editDialogRef"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="所属城市" prop="cityCode">
                <el-tree-select
                  v-model="editDialogForm.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  :render-after-expand="false"
                  node-key="Code"
                  check-strictly
                  @change="venuesByCity"
                  filterable
                  clearable
                /> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="场馆">
                <el-select
                  v-model="editDialogForm.VenuesCode"
                  placeholder="--选择--"
                  filterable
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                >
                  <el-option
                    v-for="item in activityVenuesOption"
                    :key="item.Code"
                    :label="item.CHIDescription"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="角色">
                <el-select
                  v-model="editDialogForm.Role"
                  placeholder="--请选择--"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in rolesOption"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col> </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="申请姓名" prop="applyUserName">
                <el-input
                  v-model="editDialogForm.applyUserName"
                  disabled
                /> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item prop="IsThrough" label="是否通过">
                <el-checkbox
                  v-model="editDialogForm.IsThrough"
                  :true-label="1"
                  :false-label="0"
                  @change="checkIsThrough"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="拒绝原因" prop="RefuseReason">
                <el-input
                  v-model="editDialogForm.RefuseReason"
                  :rows="3"
                  :disabled="editDialogForm.IsThrough == 1"
                  type="textarea"
                  placehoder="拒绝原因"
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="审核人" prop="ApproveUserName">
                <el-input
                  v-model="editDialogForm.ApproveUserName"
                  disabled
                  placehoder="审核人"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, toRaw } from 'vue';
import { useStore } from 'vuex';
import { Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ambulanceFormRulesMixin } from '@/utils/mixin';
import moment from 'moment';
import {
  getApplyList,
  updateApply,
  deleteApply,
  updateApplyList,
  updateApplyListDeny,
} from '@/network/applymanage';
import {
  getActivityVenues,
  getCityTree,
  getVenuesListByCityCode,
  getRoleDicByTableName,
} from '@/network/dictionary';
//搜索
const formSearch = reactive({
  activityvenuescode: null,
  cityCode: null,
  ApplyUserId: '',
  IsThrough: null,
  total: 0,
  page: 1,
  pageSize: 10,
  Role: null,
});
const store = useStore();
const rolesOption = ref([]);
//table 多选
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const batchApprove = async () => {
  if (multipleSelection.value.length > 0) {
    await updateApplyList(multipleSelection.value).then((res) => {
      initData();
      // initDict();
      ElMessage.success('审核成功');
    });
  } else {
    ElMessage.error('至少选择一个！');
  }
};
const batchDeny = async () => {
  if (multipleSelection.value.length > 0) {
    await updateApplyListDeny(multipleSelection.value).then((res) => {
      initData();
      // initDict();
      ElMessage.success('拒绝成功');
    });
  } else {
    ElMessage.error('至少选择一个！');
  }
};
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
const cs11 = async (val) => {
  //场馆赋值
  await getVenuesListByCityCode({ code: val }).then(async (res) => {
    //赋值
    activityVenuesOption.value = res;
    //清空
    formSearch.activityvenuescode = null;
  });
};
const venuesByCity = async (val) => {
  //场馆赋值
  await getVenuesListByCityCode({ code: val }).then(async (res) => {
    //赋值
    activityVenuesOption.value = res;
    //清空
    editDialogForm.value.VenuesCode = null;
  });
};
// checkbox变化
const checkIsThrough = (val) => {
  if (editDialogForm.value.IsThrough == 1) {
    editDialogForm.value.RefuseReason = '';
  }
};
//初始化数据
const ApplyUserList = ref([]);
const initData = async () => {
  let params = {
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    activityvenuescode: formSearch.activityvenuescode,
    applyUserId: formSearch.ApplyUserId,
    isThrough: formSearch.IsThrough,
    cityCode: formSearch.cityCode,
    role: formSearch.Role,
  };
  await getApplyList(params).then((res) => {
    ApplyUserList.value = res.data;
    formSearch.total = res.total;
  });
};
//初始化字典
const activityVenuesOption = ref([]);
const cityTreeOption = ref([]);
const isOnlineOption = ref([
  {
    value: 2,
    label: '未审核',
  },
  {
    value: 1,
    label: '通过',
  },
  {
    value: 0,
    label: '拒绝',
  },
]);
function timeFormat(row, column, v, i) {
  return moment(String(v)).format('YYYY-MM-DD hh:mm:ss');
}
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const initDict = async () => {
  await getActivityVenues().then((res) => {
    activityVenuesOption.value = res;
  });
  await getRoleDicByTableName({ tableName: 'trole' }).then((res) => {
    rolesOption.value = res;
  });
  //获取城市
  await getCityTree({ rootid: 0 }).then((res) => {
    cityTreeOption.value = res;
  });
};
onBeforeMount(() => {
  initDict().then(() => {
    initData();
  });
});
//搜索
const onSubmit = () => {
  formSearch.page = 1;
  initData();
};
//重置
const onReset = () => {
  formSearch.activityvenuescode = '';
  formSearch.ApplyUserId = '';
  formSearch.IsThrough = '';
  formSearch.page = 1;
  initData();
};
//分页
const handleCurrentChange = (val) => {
  formSearch.page = val;
  initData();
};
//编辑
const editDialogVisible = ref(false);
const editDialogRef = ref(null);
let editDialogForm = ref({
  VenuesCode: null,
  CityCode: null,
  Role: null,
  applyUserName: '',
  IsThrough: 1,
  cityName: '',
  venuesName: '',
  SerialNumber: null,
  RefuseReason: '',
  UpdateTime: null,
  UpdateUserID: null,
});
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  row.VenuesCode = row.VenuesCode && row.VenuesCode.split(',').map(Number);
  editDialogForm.value = JSON.parse(JSON.stringify(row));
};
// const editDislogClosed = () => {
//   editDialogForm.value = {};
// };
const editFormSubmit = async () => {
  await editDialogRef.value.validate(async (valid) => {
    if (valid) {
      let editobject = toRaw(editDialogForm.value);
      editobject.UpdateTime = rTime();
      editobject.UpdateUserID = store.state.app.userInfo.Code;
      editobject.ApproveUserID = store.state.app.userInfo.Code;
      editobject.VenuesCode = editDialogForm.value.VenuesCode?.toString();
      await updateApply(editobject)
        .then(() => {
          editDialogVisible.value = false;
          initData();
          // initDict();
          ElMessage.success('审核成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('审核失败');
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
//时间格式化
const rTime = () => {
  var date = new Date();
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = date.getDate();
  d = d < 10 ? '0' + d : d;
  var h = date.getHours();
  h = h < 10 ? '0' + h : h;
  var minute = date.getMinutes();
  minute = minute < 10 ? '0' + minute : minute;
  var s = date.getSeconds();
  s = s < 10 ? '0' + s : s;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s;
};
//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await deleteApply({ code: id })
        .then(() => {
          initData();
          initDict();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
</script>

<style lang="scss" scoped>
.userApply {
  margin: 14px 15px 14px;
  .userApply-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .userApply-list {
    margin-top: 14px;
  }
}
.uploadBtn {
  margin: 10px;
  display: inline;
}
.batchaction {
  margin: 10px;
}
</style>
